// eslint-disable-next-line @typescript-eslint/no-use-before-define
axios({
  url: 'http://localhost:8080/api/user?id=1'
  ,method:'GET'
  // @ts-ignore
}).then((res: any)=>console.log(res),(err: any)=>console.error(err))

function xhr(config: any) {
  return new PromiseX(function(resolve, reject){
    const request = new XMLHttpRequest()
    request.open(config.method, config.url, true)
    request.onreadystatechange = function(){
      if(request.readyState == 4){
        if(request.status == 200){
          resolve(request.responseText)
        }else{
          reject('请求失败')
        }
      }
    }
  })
}

function http(config: any) {
  // eslint-disable-next-line @typescript-eslint/no-var-requires
  const http = require('http')
  // eslint-disable-next-line @typescript-eslint/no-var-requires
  const url = require('url')
  const urlObject = url.parse(config.url)
  return new PromiseX(function(resolve, reject){
    const options = {
      hostname:config
      ,port:urlObject.port
      ,path:urlObject.path
      ,method:config.method
    }
    const req = http.request(options,function(response: any){
      const chunks: any = []
      response.on('data', function(chunk: any){
        chunk.push(chunk)
      })
      response.on('end',function(){
        const result = Buffer.concat(chunks).toString()
        resolve(result)
      })
    })
    req.on('error',function(error: any){
      reject(error)
    })

    req.end()
  })
}

function getDefaultAdaptor(){
  let adaptor
  if(typeof XMLHttpRequest != 'undefined'){
    adaptor = xhr
  }else if(typeof process != 'undefined'){
    adaptor = http
  }
  return adaptor
}

function axios(config: any): any{
  const adaptor = getDefaultAdaptor()
  return adaptor
}



/*
function toAxiosAdapter(options: any) {
    return axios({
        url: options.url,
        method: options.type
    }).then(options.success)
        .catch(options.error)
}


$.ajax = function (options: any) {
    return toAxiosAdapter(options)
}

$.ajax({
    url: '/api/user',
    type: 'GET',
    success: function (data: any) {
        console.log(data)
    },
    error: function (err: any) {
        console.error(err);
    }
})
*/
